﻿using Orleans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;

namespace OrleansTest
{
    public class PlayerGrain : Grain, IPlayerGrain
    {
        public PlayerGrain()
        {
            //Thread.CurrentThread.ExecutionContext
        }
        private IGameGrain currentGame;
        private ConcurrentDictionary<string, IGameGrain> gameCache = new ConcurrentDictionary<string, IGameGrain>();

        public async Task<IGameGrain> GenerateGame(string gameName)
        {
            return await Task.Run<IGameGrain>(() =>
            {
                if (!gameCache.ContainsKey(gameName))
                {
                    IGameGrain game = new GameGrain(gameName);
                    gameCache.AddOrUpdate(gameName, game, (x, y) => game);
                }
                return gameCache[gameName];
            });
        }

        // Game the player is currently in. May be null.
        public Task<IGameGrain> GetCurrentGame()
        {
            return Task.FromResult(currentGame);
        }

        // Game grain calls this method to notify that the player has joined the game.
        public Task JoinGame(IGameGrain game)
        {
            //ExecutionContext context = ExecutionContext.Capture().CreateCopy();
            //ExecutionContext.Run(context,new ContextCallback ())
            currentGame = game;
            Console.WriteLine(
                "Player {0} joined game {1}",
                this.GetPrimaryKey(),
                game.GetPrimaryKey());

            return Task.CompletedTask;
        }

       

        // Game grain calls this method to notify that the player has left the game.
        public Task LeaveGame(IGameGrain game)
        {
            currentGame = null;
            Console.WriteLine(
                "Player {0} left game {1}",
                this.GetPrimaryKey(),
                game.GetPrimaryKey());

            return Task.CompletedTask;
        }
    }
}
